package com.tg.app.activity.tools;

import static com.tg.app.TGSdkHelper.SP_PRE_CHOSE_API_ENV;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.appbase.custom.constant.CommonConstants;
import com.base.BaseActivity;
import com.demo.view.MoreClickView;
import com.tange.base.toolkit.GlobalApplicationContext;
import com.tange.core.backend.service.ep.Env;
import com.tange.core.backend.service.ep.Environment;
import com.tange.module.log.collection.AppLogManager;
import com.tg.app.R;
import com.tg.app.TGSdkHelper;
import com.tg.app.activity.device.add.SelectDeviceActivity;
import com.tg.app.fragment.BlurDialogFragment;
import com.tg.app.helper.CameraViewHelper;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tange.core.backend.service.api.CoreApiUrl;
import com.tange.core.backend.service.ep.EnvironmentProxy;
import com.tange.core.backend.service.interceptor.HttpLoggingInterceptor;
import com.tg.network.socket.http.TGHttp;

import java.util.ArrayList;

public class DevToolsActivity extends BaseActivity {

    private static final String TAG = "DevToolsActivity_";

    public static boolean enableWriteVideoDataToLocalFile = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_dev_tools);
        hideActionBar();

        initView();
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void initView() {

        findViewById(R.id.layout_logging_upload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppLogManager.getInstance().upload(DevToolsActivity.this);
            }
        });

        findViewById(R.id.modify_web_host).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });

        findViewById(R.id.back_toolbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.layout_network_detection).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> list = new ArrayList<>();
                list.add(CoreApiUrl.TG_HUB);
                list.add(PreferenceUtil.getString(TGApplicationBase.getApplication(), EnvironmentProxy.PRE_SERVER_URL));
                Intent intent = new Intent(getBaseContext(), NetworkDetectionActivity.class);
                intent.putExtra(NetworkDetectionActivity.INTENT_URL, list);
                startActivity(intent);
            }
        });


        Switch httpIntercept = findViewById(R.id.http_intercept_switch);
        httpIntercept.setChecked(HttpLoggingInterceptor.enableCache);
        httpIntercept.setOnCheckedChangeListener((buttonView, isChecked) -> {
            HttpLoggingInterceptor.updateSwitch(DevToolsActivity.this, isChecked);
            if (isChecked) {
                TGToast.showLongToast(DevToolsActivity.this,"注意打开 消息通知 权限！");
            }
        });



        Switch s = findViewById(R.id.switch_log);
        boolean isLogEnable = com.tg.app.BuildConfig.DEBUG ? true : PreferenceUtil.getBoolean(TGApplicationBase.getApplication(), TGSdkHelper.SP_PRE_LOG_ENABLE);
        s.setChecked(isLogEnable);
        if (com.tg.app.BuildConfig.DEBUG) {
            s.setAlpha(0.5f);
        }
        s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (com.tg.app.BuildConfig.DEBUG) {
                    s.setChecked(true);
                    return;
                }
                PreferenceUtil.setBooleanAsync(TGApplicationBase.getApplication(), TGSdkHelper.SP_PRE_LOG_ENABLE, isChecked);
                TGLog.setLogLevel(DevToolsActivity.this, TGLog.TYPE_VERBOSE);
            }
        });

        Switch saveVideoData = findViewById(R.id.save_video_data_switch);
        saveVideoData.setChecked(enableWriteVideoDataToLocalFile);
        saveVideoData.setOnCheckedChangeListener((buttonView, isChecked) -> {
            enableWriteVideoDataToLocalFile = isChecked;
            if (isChecked) {
                TGToast.showToast("已开启，将在APP重启后失效，有需要请重启后再次设置。");
            }
        });

        Switch apMode = findViewById(R.id.tv_ap_add_after_qrcode_switch);
        final boolean addWifiDeviceByApAfterScanQRCode = PreferenceUtil.getBoolean(TGApplicationBase.getApplication(), CommonConstants.ADD_WIFI_DEVICE_BY_AP_AFTER_SCAN_QR_CODE);
        apMode.setChecked(addWifiDeviceByApAfterScanQRCode);
        apMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            PreferenceUtil.setBooleanAsync(TGApplicationBase.getApplication(), CommonConstants.ADD_WIFI_DEVICE_BY_AP_AFTER_SCAN_QR_CODE, isChecked);
            if (isChecked) {
                TGToast.showToast("已开启");
            } else {
                TGToast.showToast("已关闭");
            }
        });

        String preChoseEnvName = Environment.INSTANCE.current().name();

        Spinner spinner = findViewById(R.id.server_select);
        spinner.setGravity(Gravity.RIGHT);
        if (Env.PRODUCT.name().equals(preChoseEnvName)) {
            spinner.setSelection(0);
        } else if (Env.PRE_PRODUCT.name().equals(preChoseEnvName)) {
            spinner.setSelection(1);
        } else {
            spinner.setSelection(2);
        }

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                Env selected = Env.valueOf(spinner.getSelectedItem().toString());
                PreferenceUtil.setStringCommit(GlobalApplicationContext.application(), SP_PRE_CHOSE_API_ENV, selected.name());
                TGHttp.reset();
                Environment.INSTANCE.configure(selected);

                String saved = PreferenceUtil.getString(GlobalApplicationContext.application(), SP_PRE_CHOSE_API_ENV, "");
                TGLog.i(TAG, "[env-setting] save = " + saved);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        MoreClickView clickView  =  findViewById(R.id.debug_enable);
       final View view  =  findViewById(R.id.layout_debug);
        boolean isEnable = PreferenceUtil.getBoolean(TGApplicationBase.getApplication(), CommonConstants.PRE_DEBUG_ENABLE);
        if (isEnable){
            view.setVisibility(View.VISIBLE);
        }
        clickView.setOnMoreClickListener(new MoreClickView.setOnMoreClickListener() {
            @Override
            public void onClick(int num, boolean enable) {
                if (enable){
                    boolean show  = false;
                    if (view.getVisibility()==View.GONE){
                        view.setVisibility(View.VISIBLE);
                        show = true;
                    }else {
                        view.setVisibility(View.GONE);
                    }
                    PreferenceUtil.setBoolean(TGApplicationBase.getApplication(), CommonConstants.PRE_DEBUG_ENABLE, show);
                }
            }
        });

        findViewById(R.id.restart_app_tv).setOnClickListener(view1 -> restartApplication());

        TextView gitVersionTv = findViewById(R.id.git_commit_version__value_tv);
        String gitVersion =  AppUtil.commitVersionCode(this);
        if (!TextUtils.isEmpty(gitVersion)){
            gitVersionTv.setTextColor(getResources().getColor(R.color.global_customize_fixed_color_dark_gray));
        }

        String versionName = AppUtil.getVersionName(this);
        int versionCode = AppUtil.getVersionCode(this);

        gitVersionTv.setText("VERSION:    " + versionName + " (" + versionCode + " | " + gitVersion + ")" + "\n"
                + "GOOGLE | DEBUG:    " + false + " | " + com.tg.app.BuildConfig.DEBUG + "\n"
                + "CORE:    " + com.tange.shell.core.BuildConfig.CORE_POM_VERSION_NAME + "\n"
                + "MODEL:    " + Build.MANUFACTURER+"-" + Build.MODEL + "\n"
                );
        Spinner talkBack2w = findViewById(R.id.sp_tv_talk_back2way);
       boolean isSupportTalkBack2w = CameraViewHelper.isTalkback2W(this);
       if (isSupportTalkBack2w){
           talkBack2w.setSelection(1);
       }else {
           talkBack2w.setSelection(0);
       }
        talkBack2w.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                CameraViewHelper.talkback2WSave(getBaseContext(),position==1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 重启应用
     */
    private void restartApplication() {
        Intent intent = getPackageManager().getLaunchIntentForPackage(getApplication().getPackageName());
        PendingIntent restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
        AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 500ms后重启应用
        System.exit(0);
    }

    private void showPopupWindow() {
        BlurDialogFragment fragment = BlurDialogFragment.newInstance();
        fragment.setBlurDialogListener(view -> {
            View mButtonView = view.findViewById(R.id.btn_scan_qrcode_next);
            final EditText editText = view.findViewById(R.id.edt_scan_qrcode_uuid);
            editText.setTextIsSelectable(true);
            editText.setTextSize(12);
            editText.setHint("输入域名，以http(s)开头，以 / 结尾");

            TextView label = view.findViewById(R.id.tv_scan_qrcode_uuid_error);
            label.setText("当前域名：" + CoreApiUrl.TG_STATIC);
            label.setVisibility(View.VISIBLE);

            InputFilter[] FilterArray = new InputFilter[1];
            FilterArray[0] = new InputFilter.LengthFilter(200);
            editText.setFilters(FilterArray);

            String customH5Url = PreferenceUtil.getString(TGApplicationBase.getApplication(), EnvironmentProxy.CUSTOM_H5_HOST);
            if (!TextUtils.isEmpty(customH5Url)) {
                editText.setText(customH5Url);
            }

            mButtonView.setOnClickListener(v -> {
                String s = editText.getText().toString().trim();
                PreferenceUtil.setString(TGApplicationBase.getApplication(), EnvironmentProxy.CUSTOM_H5_HOST, s);
                TGToast.showToast("已保存：\n" + s + "\n立即生效");
                CoreApiUrl.TG_STATIC = s;
                finish();
            });

        });
        fragment.show(getFragmentManager(), SelectDeviceActivity.class.getSimpleName());
    }
}